<template>
  <!-- 字典管理 -->
  <div class="content">
    <!-- 搜索区域 -->
    <div class="pageSearchView">
      <el-form :inline="true" :model="searchParam" class="demo-form-inline">
        <el-form-item label="字典名称">
          <el-input v-model="searchParam.name" placeholder="请输入字典名称" clearable style="width: 200px"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="getList()">查询</el-button>
          <el-button class="refreshBtn" :icon="Refresh" @click="resetSearch()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="pageTableView">
      <div class="pageTableMenuView">
        <div class="pageTableTitle">列表信息</div>
        <div class="pageTableButView">
          <el-button type="primary" :icon="Plus" @click="handleAdd()">新建</el-button>
        </div>
      </div>
      <el-table class="pageTableClass" :data="paginatedData" border height="calc(100vh - 350px)">
        <el-table-column label="序号" align="center" width="70">
          <template #default="scope">
            {{ (pageSearch.current - 1) * pageSearch.pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="name" label="字段" align="center" min-width="250"/>
        <el-table-column prop="code" label="值" align="center" min-width="250"/>
        <el-table-column prop="activate" label="是否启用" align="center" min-width="200">
          <template #default="scope">
            {{ scope.row.activate ? '启用' : '未启用' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" fixed="right" width="200">
          <template #default="scope">
            <el-button @click="handleEdit(scope.row)" type="text" size="small" plain :icon="Edit">编辑</el-button>
            <el-button @click="handleDel(scope.row)" text type="danger" size="small" :icon="Delete">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagePagination">
        <el-pagination
            background
            v-model:current-page="pageSearch.current"
            v-model:page-size="pageSearch.pageSize"
            :page-sizes="[10, 20, 50, 100, 200, 500]"
            layout="total, sizes, prev, pager, next"
            :total="pageTotal"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="showCrud" :title="crudTitle" width="800" top="5vh">
      <el-form :model="formData" label-width="90px" ref="ruleFormRef" :rules="rules" class="demo-ruleForm">
        <!-- 固定字段输入 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item
                label="字段"
                prop="name"
                :rules="[{ required: true, message: '请输入字段名', trigger: 'blur' }]"
            >
              <el-input v-model="formData.name" placeholder="请输入字段名" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12" v-if="isEdit">
            <el-form-item
                label="值"
                prop="code"
                :rules="[{ required: true, message: '请输入值', trigger: 'blur' }]"
            >
              <el-input v-model="formData.code" placeholder="请输入值" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
                label="是否启用"
                prop="activate"
                :rules="[{ required: true, message: '请选择状态', trigger: 'change' }]"
            >
              <el-select v-model="formData.activate" placeholder="请选择" style="width: 100%">
                <el-option label="启用" :value="true"/>
                <el-option label="未启用" :value="false"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 动态值列表 -->
        <div v-if="!isEdit"
             style="max-height: 500px;overflow-y: auto;overflow-x: hidden"
        >
          <el-row v-for="(item, index) in formData.values"
                  :key="index"
                  class="value-item" :gutter="20" align="middle" style="display: flex;align-items: center">
            <el-col :span="18">
              <el-form-item
                  :label="`值 ${index + 1}`"
                  :prop="`values.${index}.code`"
                  :rules="[{ required: true, message: '请输入值', trigger: 'blur' }]"
              >
                <el-input
                    v-model="item.code"
                    placeholder="请输入值"
                    clearable
                />
              </el-form-item>
            </el-col>
            <el-col :span="6" class="text-right" style="padding-bottom: 18px">
              <el-button :icon="Plus" text size="small" style="margin-left: 10px" @click="addValue"
                         v-if="index == 0">添加
              </el-button>
              <el-button :icon="Delete" text type="danger" size="small" style="margin-left: 10px"
                         @click="removeValue(index)" v-else>删除
              </el-button>
            </el-col>
          </el-row>
        </div>
      </el-form>

      <template v-slot:footer>
        <div class="dialog-footer">
          <el-button @click="showCrud = false">取消</el-button>
          <el-button type="primary" @click="handleSave(ruleFormRef)">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import {ref, reactive, computed, onMounted} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {Delete, Edit, Search, Plus, Refresh} from '@element-plus/icons-vue';
import type {FormInstance, FormRules} from 'element-plus';
import axiosInstance from "@/utils/http/api";

// 分页参数
const pageSearch = ref({
  current: 1,
  pageSize: 10
});

// 表格数据
const paginatedData = ref<any[]>([]);
const pageTotal = ref(0);
const searchParam = ref({});

// 表单相关
const showCrud = ref(false);
const isEdit = ref(false);
const ruleFormRef = ref<FormInstance>();
const crudTitle = computed(() => isEdit.value ? '编辑字典' : '新增字典');

// 表单数据结构
interface DictValue {
  code: string;
  name: string;
  activate: boolean;
}

const formData = reactive({
  name: '',
  code: '',
  activate: true,
  values: [{code: ''}] as DictValue[] // 初始包含一个空值
})


// 验证规则
const rules = reactive<FormRules>({
  // 动态规则已在模板中定义
});

// 添加值
const addValue = () => {
  formData.values.push({code: ''})
}

// 删除值
const removeValue = (index: number) => {
  formData.values.splice(index, 1)
}


// 获取字典列表
const getList = () => {
  axiosInstance.post('/api/basedata/dict/getPage', {
    ...searchParam.value,
    ...pageSearch.value
  })
      .then(res => {
        if (res.code !== 200) {
          ElMessage.error(res.message);
          return false;
        }
        paginatedData.value = res.data.records;
        pageTotal.value = res.data.total;
      });
};

// 重置搜索
const resetSearch = () => {
  searchParam.value = {};
  pageSearch.value.current = 1;
  getList();
};

// 新增字典
const handleAdd = () => {
  isEdit.value = false;
  formData.dictValues = [{code: '', name: '', activate: true}]; // 重置为一条空数据
  showCrud.value = true;
};

// 编辑字典（单条编辑，不启用批量）
const handleEdit = (row: any) => {
  Object.assign(formData, row);
  isEdit.value = true;
  showCrud.value = true;
};


const handleDel = (row: any) => {
  ElMessageBox.confirm('确定删除该条记录吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    axiosInstance.delete(`/api/basedata/dict/delete`, {
      data: {
        ids: [row.id]
      }
    }).then(res => {
      if (res.code === 200) {
        ElMessage.success('删除成功');
        getList(); // 刷新数据
      }
    });
  });
};


// 弹框确定 确认新建 确定编辑
const handleSave = async (e: FormInstance | undefined) => {
  if (!e) return;
  await e.validate((valid, fields) => {
    if (valid) {
      if (isEdit.value) {
        // 编辑
        axiosInstance.put('/api/basedata/dict/update', formData).then(res => {
          if (res.code !== 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('操作成功!');
          showCrud.value = false;
          getList(); // 刷新数据
        });
      } else {
        const list = formData.values.map(item => {
          return {
            code: item.code,
            name: formData.name,
            activate: formData.activate
          };
        });
        // 新建
        axiosInstance.post('/api/basedata/dict/saveBatch', list).then(res => {
          if (res.code !== 200) {
            ElMessage.error(res.message);
            return false;
          }
          ElMessage.success('操作成功!');
          showCrud.value = false;
          getList(); // 刷新数据
        });
      }

    }
  });
};


const handleSizeChange = (e) => {
  pageSearch.value.pageSize = e;
  getList();
};

const handleCurrentChange = (e) => {
  pageSearch.value.current = e;
  getList();
};

// 初始化
onMounted(() => {
  getList();
});
</script>

<style scoped>
/* 保持原有样式 */
</style>